import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'single_chat_controller.dart';
import '../../function/model/single_chat_message_model.dart';
import '../../function/utils/my_common.dart';

/// 单聊聊天页面
class SingleChatPage extends GetView<SingleChatController> {
  const SingleChatPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/communal_bg.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              _buildTopBar(),
              Expanded(child: _buildMessageList()),
              _buildInputArea(),
            ],
          ),
        ),
      ),
    );
  }

  /// 顶部导航栏（返回 + 对端头像/昵称）
  Widget _buildTopBar() {
    return GetX<SingleChatController>(
      builder: (controller) {
        final chat = controller.currentChat;
        if (chat == null) return const SizedBox.shrink();
        final other = controller.getOtherUser();

        return Container(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
          child: Row(
            children: [
              GestureDetector(
                onTap: () => Get.back(),
                child: Icon(
                  Icons.arrow_back_ios_new,
                  size: 20.sp,
                  color: MyCommonUtils.white,
                ),
              ),

              Expanded(
                child: Center(
                  child: Text(
                    other != null
                        ? (other.nickname.isNotEmpty
                            ? other.nickname
                            : other.username)
                        : 'Chat',
                    style: TextStyle(
                      fontSize: 18.sp,
                      fontWeight: FontWeight.w700,
                      color: MyCommonUtils.white,
                      fontFamily:
                          GoogleFonts.berkshireSwash(
                            fontWeight: FontWeight.w700,
                          ).fontFamily,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ),

              // 举报按钮
              GestureDetector(
                onTap: controller.reportCurrentChat,
                child: Image.asset(
                  'assets/images/report.png',
                  width: 24.w,
                  height: 24.w,
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  /// 消息列表
  Widget _buildMessageList() {
    return GetX<SingleChatController>(
      builder: (controller) {
        final messages = controller.getCurrentChatMessages();
        if (messages.isEmpty) {
          return Center(
            child: Text(
              'No messages yet. Say hi!',
              style: TextStyle(
                fontSize: 16.sp,
                color: MyCommonUtils.white.withValues(alpha: 0.7),
              ),
            ),
          );
        }

        return ListView.builder(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
          itemCount: messages.length,
          itemBuilder: (context, index) {
            final message = messages[index];
            return _buildMessageItem(message);
          },
        );
      },
    );
  }

  /// 单条消息
  Widget _buildMessageItem(SingleChatMessageModel message) {
    final isCurrentUser = controller.isCurrentUser(message.senderId);
    final user = controller.getUserById(message.senderId);

    return Container(
      margin: EdgeInsets.only(bottom: 20.h),
      child: Row(
        mainAxisAlignment:
            isCurrentUser ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!isCurrentUser) ...[
            CircleAvatar(
              radius: 25.w,
              backgroundImage: AssetImage(
                user?.avatar ?? 'assets/images/avatar1.png',
              ),
            ),
            SizedBox(width: 8.w),
          ],
          Flexible(
            child: Container(
              constraints: BoxConstraints(maxWidth: Get.width * 0.75),
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
              decoration: BoxDecoration(
                color:
                    isCurrentUser ? MyCommonUtils.orange : MyCommonUtils.white,
                borderRadius: BorderRadius.circular(20.r),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    message.content,
                    style: TextStyle(
                      fontSize: 14.sp,
                      color:
                          isCurrentUser
                              ? MyCommonUtils.white
                              : MyCommonUtils.black,
                      height: 1.4,
                    ),
                  ),
                  SizedBox(height: 4.h),
                ],
              ),
            ),
          ),
          if (isCurrentUser) ...[
            SizedBox(width: 8.w),
            CircleAvatar(
              radius: 25.w,
              backgroundImage: AssetImage(controller.getCurrentUserAvatar()),
            ),
          ],
        ],
      ),
    );
  }

  /// 输入区域
  Widget _buildInputArea() {
    return Container(
      padding: EdgeInsets.all(16.w),
      child: GetX<SingleChatController>(
        builder: (controller) {
          return Container(
            decoration: BoxDecoration(
              color: MyCommonUtils.white.withValues(alpha: 0.9),
              borderRadius: BorderRadius.circular(25.r),
            ),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: controller.messageController,
                    focusNode: controller.messageFocusNode,
                    decoration: InputDecoration(
                      hintText: 'Say something',
                      hintStyle: TextStyle(
                        fontSize: 14.sp,
                        color: MyCommonUtils.grey,
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(
                        horizontal: 20.w,
                        vertical: 12.h,
                      ),
                    ),
                    maxLines: null,
                    textInputAction: TextInputAction.send,
                    onSubmitted: (_) => controller.sendMessage(),
                    enabled: !controller.isSending,
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(right: 8.w),
                  child: GestureDetector(
                    onTap: controller.sendMessage,
                    child: Image.asset(
                      'assets/images/comment_send.png',
                      width: 32.w,
                      height: 32.w,
                    ),
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}
